# -*- coding: utf-8 -*-
"""
 * @file main.py
 * @author SDK_TEAM
 * @brief
 * @version 0.1
 * @date 2024-05-31
 * Copyright:
 * © 2018 北京灵汐科技有限公司 版权所有。
 * 注意：以下内容均为北京灵汐科技有限公司原创，未经本公司允许，不得转载，否则将视为侵权；对于不遵守此声明或者其他违法使用以下内容者，本公司依法保留追究权。
 * © 2018 Lynxi Technologies Co., Ltd. All rights reserved.
 * NOTICE: All information contained here is, and remains the property of Lynxi. This file can not
 * be copied or distributed without the permission of Lynxi Technologies Co., Ltd.
"""

import multiprocessing
import signal
import sys
import json

sys.path.append("../../../")
from ctypes import *
import argparse
import common.python.common as common
import struct
import pylynchipsdk as sdk
from common.python.plugin_utils import *
from common.python.infer_process import *
from common.python.callback_data_struct import *
import ctypes


# Create a shared boolean value to stop running thread
cancel_flag = multiprocessing.Value("b", False)
pythonapi.PyCapsule_GetPointer.restype = c_void_p
pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p]


def save_boxinfo_cb(params):
    output_path = params[0]
    boxex_info = params[1]
    eos = params[2]
    if eos:
        return 0

    dst_img_size = ctypes.sizeof(Box)
    host_buf_arr = np.ones(dst_img_size, dtype=np.uint8)
    host_buf = sdk.lyn_numpy_to_ptr(host_buf_arr)
    ret = sdk.lyn_memcpy(
        host_buf, boxex_info, dst_img_size, sdk.lyn_memcpy_dir_t.ServerToClient
    )
    common.error_check(ret, "save_boxinfo_cb lyn_memcpy")
    host_buf_c = pythonapi.PyCapsule_GetPointer(host_buf, None)
    c_box = ctypes.cast(host_buf_c, ctypes.POINTER(Box)).contents
    dump_box_json(output_path, c_box)
    return 0


def dump_box_json(output_path, c_box):
    box_dict = {"boxesnum": c_box.boxesnum, "boxes": []}
    for i in range(c_box.boxesnum):
        bbox_instance = c_box.boxes[i]
        bbox_dict = {
            "xmin": bbox_instance.xmin,
            "ymin": bbox_instance.ymin,
            "xmax": bbox_instance.xmax,
            "ymax": bbox_instance.ymax,
            "score": bbox_instance.score,
            "label": bbox_instance.label.decode("utf-8"),
        }
        box_dict["boxes"].append(bbox_dict)

    # Serialize the dictionary to JSON
    with open(output_path, "a", encoding="utf-8") as f:
        f.seek(0, os.SEEK_END)
        file_size = f.tell()
        if file_size < 500 * 1024 * 1024:
            json.dump(box_dict, f, indent=2, ensure_ascii=False)
            f.write("\n")
        else:
            print("only support 500M.", output_path, "now file size:", file_size)


class yolov5s6(infer_process):
    def __init__(self, attr):
        super().__init__(attr)
        self.label_file = attr.label_file
        self.boxes_info, ret = sdk.lyn_malloc(ctypes.sizeof(Box))
        common.error_check(ret)
        self.label_list, self.label_info_dev = create_label_list_with_names(
            attr.label_file
        )
        self.post_plugin, ret = sdk.lyn_plugin_register(attr.post_plugin)
        common.error_check(ret, "lyn_plugin_register")
        self.osd_plugin, ret = sdk.lyn_plugin_register(attr.osd_plugin)
        common.error_check(ret, "lyn_plugin_register")

    def before_ctx_destroy(self):
        common.error_check(sdk.lyn_free(self.boxes_info))
        common.error_check(sdk.lyn_free(self.label_info_dev))

        ret = sdk.lyn_plugin_unregister(self.post_plugin)
        common.error_check(ret, "lyn_plugin_unregister")
        ret = sdk.lyn_plugin_unregister(self.osd_plugin)
        common.error_check(ret, "lyn_plugin_unregister")

    def set_padding_data(self, video_width, video_heigh, model_width, model_height):
        fScaleW = float(model_width) / float(video_width)
        fScaleH = float(model_height) / float(video_heigh)
        fScale = min(fScaleW, fScaleH)
        self.m_iResizeWidth = int(float(video_width) * fScale) & ~1
        self.m_iResizeHeight = int(float(video_heigh) * fScale) & ~1

        if self.m_iResizeWidth > 1920 or self.m_iResizeHeight > 1080:
            fScaleW = 1920 / float(model_width)
            fScaleH = 1080 / float(model_height)
            fScale = fScale * min(fScaleW, fScaleH)
            self.m_iResizeWidth = int(float(video_width) * fScale) & ~1
            self.m_iResizeHeight = int(float(video_heigh) * fScale) & ~1

        return int(self.m_iResizeWidth), int(self.m_iResizeHeight), 0, 0

    def ipe_process(self, cb_data: framepool_cb_data):
        sdk.lyn_set_current_context(self.get_ctx())
        ipe_out_data = self.ipe_output_mem_pool.pop()
        sdk.lyn_memset(ipe_out_data, 0, self.ipe_output_mem_pool.elemsize)
        # 设置ipe输入
        ret = sdk.lyn_ipe_set_input_pic_desc(
            self.ipe_input_desc,
            cb_data.frame.data,
            self.vdec_out_info.width,
            self.vdec_out_info.height,
            self.get_vdec_attr().output_fmt,
        )
        common.error_check(ret, "lyn_ipe_set_input_pic_desc")
        ret = sdk.lyn_ipe_set_output_pic_data(
            self.ipe_output_desc, ipe_out_data)
        common.error_check(ret, "lyn_ipe_set_output_pic_data")

        ret = sdk.lyn_ipe_set_c2c_config(
            self.ipe_config, sdk.lyn_pixel_format_t.LYN_PIX_FMT_RGB24, 0
        )
        common.error_check(ret, "lyn_ipe_set_c2c_config")

        ret = sdk.lyn_ipe_set_resize_config(
            self.ipe_config, self.resize_width, self.resize_height
        )
        common.error_check(ret, "lyn_ipe_set_resize_config")

        ret = sdk.lyn_ipe_cal_output_pic_desc(
            self.ipe_output_desc, self.ipe_input_desc, self.ipe_config, 0
        )
        common.error_check(ret, "lyn_ipe_cal_output_pic_desc")
        ret = sdk.lyn_ipe_process_async(
            self.ipe_stream, self.ipe_input_desc, self.ipe_output_desc, self.ipe_config
        )
        common.error_check(ret, "lyn_ipe_process_async")

        return ipe_out_data

    def plugin_process(self, apu_output_data, cb_data):
        # 等待apu处理完成
        ret = sdk.lyn_record_event(self.apu_stream, self.apu_event)
        common.error_check(ret, "lyn_record_event")
        ret = sdk.lyn_stream_wait_event(self.plugin_stream, self.apu_event)
        common.error_check(ret, "lyn_stream_wait_event")
        pythonapi.PyCapsule_GetPointer.restype = c_void_p
        pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p]
        apu_data_ptr = pythonapi.PyCapsule_GetPointer(apu_output_data, None)
        frame_data_ptr = pythonapi.PyCapsule_GetPointer(cb_data.frame.data, None)
        boxes_info_ptr = pythonapi.PyCapsule_GetPointer(self.boxes_info, None)

        post_para = YoloxPostProcessInfo_t()
        post_para.height = self.model_height
        post_para.width = self.model_width
        post_para.ori_height = self.codec_para.height
        post_para.ori_width = self.codec_para.width
        post_para.score_threshold = 0.25
        post_para.nms_threshold = 0.45
        post_para.nms_top_k = 500
        post_para.is_pad_resize = 1
        post_para.output_tensor = apu_data_ptr
        post_para.class_num = self.label_list.labelNum
        post_para.labelList = self.label_list
        post_para.boxesInfo = boxes_info_ptr
        post_para.anchorSize = 3

        yolox_data = ctypes.string_at(
            ctypes.addressof(post_para), ctypes.sizeof(post_para)
        )
        ret = sdk.lyn_plugin_run_async(
            self.plugin_stream,
            self.post_plugin,
            "lynYoloxPostProcess",
            yolox_data,
            ctypes.sizeof(YoloxPostProcessInfo_t),
        )
        common.error_check(ret, "lyn_plugin_run_async")

        if self.attr.show_type == 2:
            ret = sdk.lyn_stream_add_callback(
                self.plugin_stream,
                save_boxinfo_cb,
                [self.attr.output_path, self.boxes_info, cb_data.frame.eos],
            )
        else:
            osd_para = struct.pack(
                "1P3i1P4i",
                boxes_info_ptr,
                self.codec_para.width,
                self.codec_para.height,
                sdk.lyn_pixel_format_t.LYN_PIX_FMT_NV12,
                frame_data_ptr,
                24,
                4,
                2,
                4,
            )
            common.error_check(
                sdk.lyn_plugin_run_async(
                    self.plugin_stream,
                    self.osd_plugin,
                    "lynDrawBoxAndText",
                    osd_para,
                    len(osd_para),
                )
            )

        ret = sdk.lyn_stream_add_callback(
            self.plugin_stream,
            free_to_pool_callback,
            [self.apu_output_mem_pool, apu_output_data],
        )
        common.error_check(ret, "lyn_stream_add_callback")

    def run(self, attr: infer_process_attr):
        super().run(attr)


def main(args, video_frame) -> None:
    attr = infer_process_attr()
    attr.url = args.input_path
    if args.show_type == 1:
        attr.output_path = common.append_text_to_filename(
            common.change_file_extension(args.input_path, ".264"),
            f"_device_{args.device_id}_channel_{args.channel_id}",
        )
    elif args.show_type == 2:
        attr.output_path = common.append_text_to_filename(
            common.change_file_extension(args.input_path, ".json"),
            f"_device_{args.device_id}_channel_{args.channel_id}",
        )
    if not os.path.isfile(attr.url):
        attr.output_path = attr.output_path.replace("/", "_").replace(":", "_")
    if os.path.exists(attr.output_path):
        os.remove(attr.output_path)
    attr.device_id = args.device_id
    attr.chan_id = args.channel_id
    attr.plugin_path = args.post_plugin
    attr.model_path = args.model_path
    attr.show_type = args.show_type
    attr.video_frame = video_frame
    attr.osd_plugin = args.osd_plugin
    attr.post_plugin = args.post_plugin
    attr.label_file = args.label_file
    if not attr.url:
        raise ValueError("input file miss!!!")
    if attr.show_type == 1 and not attr.output_path:
        raise ValueError("unspecified output path!!!")
    yolov5s6_worker = yolov5s6(attr)
    yolov5s6_worker.run(cancel_flag)
    yolov5s6_worker.close()


def cancel_process(signum, frame):
    global cancel_flag
    cancel_flag.value = True


if __name__ == "__main__":
    argparser = argparse.ArgumentParser(description="python3 main.py ")
    argparser.add_argument("-m", "--model_path", type=str, help="model file path")
    argparser.add_argument("-i", "--input_path", help="input video path or stream url")
    argparser.add_argument("-p", "--post_plugin", type=str, help="plugin path")
    argparser.add_argument("-o", "--osd_plugin", type=str, help="plugin path")
    argparser.add_argument("-l", "--label_file", type=str, help="plugin path")
    argparser.add_argument(
        "-d",
        "--device_id",
        type=str,
        default="0",
        help='Comma-separated list of device ids, e.g., "0,1"',
    )
    argparser.add_argument("-s", "--show_type", type=int, default=0, help="show type")
    argparser.add_argument(
        "-c", "--channel_num", type=int, default=1, help="channel_num"
    )

    signal.signal(signal.SIGINT, cancel_process)
    args = argparser.parse_args()
    args.config_file = None
    channel_infos = get_channel_infos(args)
    start_process(main, channel_infos, cancel_flag)
